import datetime

from django.contrib.auth.models import User
from django.db import models
# Create your models here.
from cate import settings


class DictMixin:
    """queryset转字典"""
    def to_dict(self):
        fields = []
        for field in self._meta.fields:
            fields.append(field.name)

        d = {}
        for attr in fields:
            if isinstance(getattr(self, attr), datetime.datetime):
                d[attr] = getattr(self, attr).strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(getattr(self, attr), datetime.date):
                d[attr] = getattr(self, attr).strftime('%Y-%m-%d')
            elif isinstance(getattr(self, attr), DictMixin):
                d[attr] = getattr(self, attr).to_dict()
            elif isinstance(getattr(self, attr), User):
                d[attr] = getattr(self,attr).username
            else:
                d[attr] = getattr(self, attr)
        return d


class BaseModel(models.Model, DictMixin):
    """model 基类"""
    is_valid = models.BooleanField(default=False, verbose_name="是否有效")
    remarks = models.TextField(null=True, blank=True, verbose_name='备注')
    create_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    modified_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    # changed_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL,)
    # history = HistoricalRecords(inherit=True)
    #
    # @property
    # def _history_user(self):
    #     return self.changed_by
    #
    # @_history_user.setter
    # def _history_user(self, value):
    #     self.changed_by = value

    class Meta:
        abstract = True